import React, { useEffect, useState } from "react";
import {
  Card,
  Button,
  Progress,
  Space,
  Tag,
  Modal,
  message,
  Layout,
  Avatar,
} from "antd";
import { RobotOutlined, UserOutlined } from "@ant-design/icons";
import { useStore } from "../../stores/store";
import { getAIAdviceApi } from "../../api/ai";
import Typewriter from "../Typewriter";
const Resume = () => {
  const { state, getUserInfo } = useStore();
  const [avatarUrl, setAvatarUrl] = useState("");
  const userInfo = state.userInfo || {};
  const { Content, Sider } = Layout;
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [aiAdvice, setAiAdvice] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    // 组件加载时获取用户信息
    getUserInfo();
  }, []);
  useEffect(() => {
    if (state.userInfo?.avatar) {
      // 添加时间戳防止缓存
      const timestamp = new Date().getTime();
      setAvatarUrl(
        `${import.meta.env.VITE_APP_MEDIA_URL}/${
          state.userInfo.avatar
        }?t=${timestamp}`
      );
    }
  }, [state.userInfo]);
  // 计算简历完整度
  const calculateCompletionRate = () => {
    const totalFields = 10; // 总字段数
    let completedFields = 0;

    // 检查基本信息
    if (userInfo.real_name) completedFields++;
    if (userInfo.gender) completedFields++;
    if (userInfo.phone) completedFields++;
    if (userInfo.email) completedFields++;
    if (userInfo.avatar) completedFields++;

    // 检查求职期望
    if (userInfo.expectation?.job_name) completedFields++;
    if (userInfo.expectation?.money) completedFields++;
    if (userInfo.expectation?.place) completedFields++;
    if (userInfo.expectation?.industry) completedFields++;

    return Math.floor((completedFields / totalFields) * 100);
  };

  // 获取AI建议
  const getAIAdvice = async () => {
    try {
      setIsLoading(true);
      setIsModalVisible(true);
      // 收集简历信息
      const resumeContent = `
        姓名：${userInfo.real_name || "未设置"}
        性别：${userInfo.gender || "未设置"}
        年龄：${userInfo.age || "未设置"}
        工作经验：${userInfo.experience || "暂无"}
        求职期望：
        - 职位：${userInfo.expectation?.job_name || "未设置"}
        - 薪资：${
          userInfo.expectation?.money
            ? `${userInfo.expectation.money}k/月`
            : "待定"
        }
        - 地点：${userInfo.expectation?.place || "未设置"}
        - 行业：${userInfo.expectation?.industry || "未设置"}
        工作经历：${
          userInfo.jobs?.length
            ? userInfo.jobs
                .map(
                  (job) => `
              公司：${job.company}
              职位：${job.position}
              时间：${job.duration}
            `
                )
                .join("\n")
            : "暂无工作经历"
        }
      `;

      const response = await getAIAdviceApi(resumeContent);
      setAiAdvice(response.advice);
    } catch (error) {
      message.error("获取AI建议失败，请重试");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Layout
      style={{
        maxWidth: "1400px",
        margin: "0 auto",
        height: "89vh",
        background: "#f5f5f5",
      }}
    >
      {/* 左侧简历主体 */}
      <Content
        style={{
          flex: 3,
          padding: "20px",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          className="scroll-container"
          style={{ flex: 1, overflowY: "auto" }}
        >
          <Card>
            {/* 基本信息 */}
            <div style={{ display: "flex", marginBottom: 24 }}>
              <div style={{ marginRight: 24 }}>
                <Avatar
                  src={avatarUrl || null}
                  icon={!avatarUrl && <UserOutlined />}
                />
              </div>
              <div>
                <h2>
                  {userInfo.real_name || "未设置"}
                  <Tag color="blue" style={{ marginLeft: 8 }}>
                    编辑
                  </Tag>
                </h2>
                <Space split="·" style={{ color: "#666" }}>
                  <span>{userInfo.age || "--"}岁</span>
                  <span>{userInfo.experience || "暂无经验"}</span>
                  <span>{userInfo.expectation.place || "未设置地址"}</span>
                </Space>
                <p style={{ marginTop: 8, color: "#666" }}>
                  {userInfo.status || "未设置求职状态"}
                </p>
                <p>{userInfo.phone || "未设置联系方式"}</p>
              </div>
            </div>

            {/* 求职期望 */}
            <Card title="求职期望" type="inner" style={{ marginBottom: 16 }}>
              <Space split="·">
                <span>{userInfo.expectation?.job_name || "未设置"}</span>
                <span>
                  {userInfo.expectation?.money
                    ? `${userInfo.expectation.money}k/月`
                    : "待定"}
                </span>
                <span>{userInfo.expectation?.place || "未设置"}</span>
                <span>{userInfo.expectation?.industry || "未设置"}</span>
              </Space>
            </Card>

            {/* 工作经历 */}
            <Card title="工作经历" type="inner">
              {userInfo.jobs?.length > 0 ? (
                userInfo.jobs.map((job, index) => (
                  <div key={index} style={{ marginBottom: 16 }}>
                    <h4>{job.company}</h4>
                    <p style={{ color: "#666" }}>{job.duration}</p>
                    <p>{job.position}</p>
                  </div>
                ))
              ) : (
                <p style={{ color: "#666" }}>暂无工作经历</p>
              )}
            </Card>
          </Card>
        </div>
      </Content>

      {/* 右侧完整度 */}
      <Sider
        width={400}
        style={{
          background: "transparent",
          padding: "20px",
          marginTop: "50px",
          overflow: "hidden",
        }}
      >
        <Card>
          <h3>中文简历完整度</h3>
          <Progress percent={calculateCompletionRate()} />
          <p style={{ textAlign: "center", color: "#666" }}>
            持续优化简历，获更强职场竞争力
          </p>

          {/* 待完善项 */}
          <div style={{ marginTop: 24 }}>
            <h4>
              简历待完善项{" "}
              <Tag color="orange">{10 - calculateCompletionRate() / 10}</Tag>
            </h4>
            <ul style={{ paddingLeft: 20 }}>
              {!userInfo.real_name && (
                <li>
                  基本信息 <Tag color="red">必填字段缺失</Tag>
                </li>
              )}
              {!userInfo.expectation?.job_name && (
                <li>
                  求职期望 <Tag color="red">必填字段缺失</Tag>
                </li>
              )}
              {!userInfo.jobs?.length && (
                <li>
                  工作经历 <Tag>未填写</Tag>
                </li>
              )}
            </ul>
          </div>

          <Button
            type="primary"
            icon={<RobotOutlined />}
            onClick={getAIAdvice}
            style={{ marginTop: 16, width: "100%" }}
          >
            获取BOSS求职建议
          </Button>
        </Card>
      </Sider>

      {/* AI建议弹窗 */}
      <Modal
        title="BOSS为你推荐岗位"
        open={isModalVisible}
        footer={null}
        onCancel={() => {
          setIsModalVisible(false);
          setAiAdvice("");
        }}
        width={600}
        className="ai-advice-modal scroll-container"
      >
        <Typewriter
          text={aiAdvice}
          speed={50}
          className="typewriter-text"
          loading={isLoading}
        />
      </Modal>
    </Layout>
  );
};

export default Resume;
